package com.qiuzhi.spring;

import com.qiuzhi.spring.annotations.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

@Component
public class QiuzhiBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
//        System.out.println("初始化之前");
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        //匹配
        if (beanName.equals("userService")) {
            Object proxyBean = Proxy.newProxyInstance(QiuzhiBeanPostProcessor.class.getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    System.out.println("之前");
                    Object result = method.invoke(bean, args);
                    System.out.println("之后");
                    return result;
                }
            });
            return proxyBean;
        }
        return bean;
    }
}
